#include "RegisterWindow.hpp"
#include "LoginWindow.hpp"
#include "UsersRegister.hpp"
#include "tools/Hash.hpp"
#include "tools/Logger.hpp"
#include <QApplication>
#include <QFormLayout>
#include <QHBoxLayout>
#include <QMessageBox>
#include <QRegularExpression>
#include <QRegularExpressionValidator>
#include <QScreen>
#include <QScrollArea>
#include <string>

RegisterWindow::RegisterWindow(QWidget *parent) : QMainWindow(parent) {
  setupUI();
  setupConnections();
  populateProvinces();
  populateMajors();
  setWindowTitle("注册账号");
}

RegisterWindow::~RegisterWindow() {}

void RegisterWindow::setupUI() {
  centralWidget = new QWidget(this);
  setCentralWidget(centralWidget);

  // 使用滚动区域来处理内容溢出
  QScrollArea *scrollArea = new QScrollArea(centralWidget);
  scrollArea->setWidgetResizable(true);
  scrollArea->setFrameShape(QFrame::NoFrame);

  QWidget *scrollContent = new QWidget(scrollArea);
  scrollArea->setWidget(scrollContent);

  mainLayout = new QVBoxLayout(scrollContent);
  mainLayout->setContentsMargins(50, 50, 50, 50);
  mainLayout->setSpacing(20);

  // 标题和副标题
  titleLabel = new QLabel("创建账号", scrollContent);
  titleLabel->setStyleSheet(
      "font-size: 56px; font-weight: bold; color: #2196F3;");
  titleLabel->setAlignment(Qt::AlignCenter);

  subtitleLabel = new QLabel("请填写以下信息完成注册", scrollContent);
  subtitleLabel->setStyleSheet("font-size: 48px; color: #666;");
  subtitleLabel->setAlignment(Qt::AlignCenter);

  // 注册表单
  QWidget *formWidget = new QWidget(scrollContent);
  QFormLayout *formLayout = new QFormLayout(formWidget);
  formLayout->setSpacing(15);

  // 用户名输入框
  userNameEdit = new QLineEdit(formWidget);
  userNameEdit->setPlaceholderText("请输入用户名");
  userNameEdit->setStyleSheet("QLineEdit { padding: 10px; border: 1px solid "
                              "#ddd; border-radius: 5px; font-size: 28px; }");
  formLayout->addRow("用户名:", userNameEdit);

  // 手机号输入框
  phoneEdit = new QLineEdit(formWidget);
  phoneEdit->setPlaceholderText("请输入手机号码");
  phoneEdit->setValidator(new QRegularExpressionValidator(
      QRegularExpression("^1[3-9]\\d{9}$"), this));
  phoneEdit->setStyleSheet("QLineEdit { padding: 10px; border: 1px solid #ddd; "
                           "border-radius: 5px; font-size: 28px; }");
  formLayout->addRow("手机号码:", phoneEdit);

  // 邮箱输入框
  emailEdit = new QLineEdit(formWidget);
  emailEdit->setPlaceholderText("请输入电子邮箱");
  emailEdit->setStyleSheet("QLineEdit { padding: 10px; border: 1px solid #ddd; "
                           "border-radius: 5px; font-size: 28px; }");
  formLayout->addRow("电子邮箱:", emailEdit);

  // 密码输入框
  passwordEdit = new QLineEdit(formWidget);
  passwordEdit->setPlaceholderText("请设置密码");
  passwordEdit->setEchoMode(QLineEdit::Password);
  passwordEdit->setStyleSheet("QLineEdit { padding: 10px; border: 1px solid "
                              "#ddd; border-radius: 5px; font-size: 28px; }");
  formLayout->addRow("密码:", passwordEdit);

  // 确认密码输入框
  confirmPasswordEdit = new QLineEdit(formWidget);
  confirmPasswordEdit->setPlaceholderText("请再次输入密码");
  confirmPasswordEdit->setEchoMode(QLineEdit::Password);
  confirmPasswordEdit->setStyleSheet(
      "QLineEdit { padding: 10px; border: 1px solid #ddd; border-radius: 5px; "
      "font-size: 28px; }");
  formLayout->addRow("确认密码:", confirmPasswordEdit);

  // 省份选择下拉框
  provinceComboBox = new QComboBox(formWidget);
  provinceComboBox->setStyleSheet(
      "QComboBox { padding: 10px; border: 1px solid #ddd; border-radius: 5px; "
      "font-size: 28px; }");
  formLayout->addRow("所在省份:", provinceComboBox);

  // 高考分数输入框
  pointsEdit = new QLineEdit(formWidget);
  pointsEdit->setPlaceholderText("请输入高考分数");
  pointsEdit->setValidator(new QRegularExpressionValidator(
      QRegularExpression("^[0-9]{1,3}$"), this));
  pointsEdit->setStyleSheet("QLineEdit { padding: 10px; border: 1px solid "
                            "#ddd; border-radius: 5px; font-size: 28px; }");
  formLayout->addRow("高考分数:", pointsEdit);

  // 意向专业选择下拉框
  majorComboBox = new QComboBox(formWidget);
  majorComboBox->setStyleSheet("QComboBox { padding: 10px; border: 1px solid "
                               "#ddd; border-radius: 5px; font-size: 28px; }");
  formLayout->addRow("意向专业:", majorComboBox);

  // 注册按钮
  registerButton = new QPushButton("注册", scrollContent);
  registerButton->setStyleSheet(
      "QPushButton { background-color: #2196F3; color: white; border: none; "
      "padding: 10px; border-radius: 5px; font-size: 48px; } "
      "QPushButton:hover { background-color: #0b7dda; }");
  registerButton->setMinimumHeight(40);

  // 返回登录按钮
  backToLoginButton = new QPushButton("已有账号? 返回登录", scrollContent);
  backToLoginButton->setStyleSheet("QPushButton { background: none; border: "
                                   "none; color: #2196F3; font-size: 28px; } "
                                   "QPushButton:hover { color: #0b7dda; }");
  QHBoxLayout *backToLoginLayout = new QHBoxLayout();
  backToLoginLayout->addWidget(backToLoginButton, 0, Qt::AlignCenter);
  mainLayout->addLayout(backToLoginLayout);

  // 添加所有组件到主布局
  mainLayout->addWidget(titleLabel);
  mainLayout->addWidget(subtitleLabel);
  mainLayout->addSpacing(20);
  mainLayout->addWidget(formWidget);
  mainLayout->addSpacing(20);
  mainLayout->addWidget(registerButton);
  mainLayout->addSpacing(10);
  mainLayout->addWidget(backToLoginButton);

  // 设置滚动区域为中央部件的布局
  QVBoxLayout *centralLayout = new QVBoxLayout(centralWidget);
  centralLayout->setContentsMargins(0, 0, 0, 0);
  centralLayout->addWidget(scrollArea);
  centralWidget->setLayout(centralLayout);

  QScreen *screen = QGuiApplication::primaryScreen();
  QRect screenGeometry = screen->geometry();
  int screenWidth = screenGeometry.width();
  int screenHeight = screenGeometry.height();

  // 设置窗口大小为屏幕的60%
  int windowWidth = static_cast<int>(screenWidth * 0.6);
  int windowHeight = static_cast<int>(screenHeight * 0.6);
  resize(windowWidth, windowHeight);

  setStyleSheet("background-color: #f8f8f8;");
}

void RegisterWindow::setupConnections() {
  connect(registerButton, &QPushButton::clicked, this,
          &RegisterWindow::onRegisterButtonClicked);
  connect(backToLoginButton, &QPushButton::clicked, this,
          &RegisterWindow::onBackToLoginClicked);
}

void RegisterWindow::populateProvinces() {
  // 添加中国的省份
  QStringList provinces = {
      "北京市",         "天津市",        "上海市",         "重庆市",
      "河北省",         "山西省",        "辽宁省",         "吉林省",
      "黑龙江省",       "江苏省",        "浙江省",         "安徽省",
      "福建省",         "江西省",        "山东省",         "河南省",
      "湖北省",         "湖南省",        "广东省",         "海南省",
      "四川省",         "贵州省",        "云南省",         "陕西省",
      "甘肃省",         "青海省",        "台湾省",         "内蒙古自治区",
      "广西壮族自治区", "西藏自治区",    "宁夏回族自治区", "新疆维吾尔自治区",
      "香港特别行政区", "澳门特别行政区"};
  provinceComboBox->addItems(provinces);
}

void RegisterWindow::populateMajors() {
  // 添加常见大学专业
  QStringList majors = {"计算机科学与技术",
                        "软件工程",
                        "人工智能",
                        "数据科学与大数据技术",
                        "网络空间安全",
                        "电子信息工程",
                        "通信工程",
                        "机械工程",
                        "自动化",
                        "电气工程及其自动化",
                        "土木工程",
                        "建筑学",
                        "城市规划",
                        "环境工程",
                        "给排水科学与工程",
                        "临床医学",
                        "基础医学",
                        "药学",
                        "护理学",
                        "口腔医学",
                        "工商管理",
                        "市场营销",
                        "会计学",
                        "财务管理",
                        "人力资源管理",
                        "法学",
                        "政治学与行政学",
                        "社会学",
                        "经济学",
                        "金融学",
                        "数学与应用数学",
                        "物理学",
                        "化学",
                        "生物科学",
                        "地理科学",
                        "汉语言文学",
                        "英语",
                        "日语",
                        "新闻学",
                        "广告学"};
  majorComboBox->addItems(majors);
}

bool RegisterWindow::validateInput() {
  if (userNameEdit->text().isEmpty()) {
    QMessageBox::warning(this, "注册失败", "请输入用户名");
    return false;
  }
  if (phoneEdit->text().isEmpty()) {
    QMessageBox::warning(this, "注册失败", "请输入手机号码");
    return false;
  }
  if (emailEdit->text().isEmpty()) {
    QMessageBox::warning(this, "注册失败", "请输入电子邮箱");
    return false;
  } else {
    // 简单的邮箱格式验证
    QRegularExpression emailRegex(
        "\\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}\\b",
        QRegularExpression::CaseInsensitiveOption);
    if (!emailRegex.match(emailEdit->text()).hasMatch()) {
      QMessageBox::warning(this, "注册失败", "电子邮箱格式不正确");
      return false;
    }
  }
  if (passwordEdit->text().isEmpty()) {
    QMessageBox::warning(this, "注册失败", "请设置密码");
    return false;
  }
  if (confirmPasswordEdit->text().isEmpty()) {
    QMessageBox::warning(this, "注册失败", "请确认密码");
    return false;
  }
  if (passwordEdit->text() != confirmPasswordEdit->text()) {
    QMessageBox::warning(this, "注册失败", "两次输入的密码不一致");
    return false;
  }
  if (pointsEdit->text().isEmpty()) {
    QMessageBox::warning(this, "注册失败", "请输入高考分数");
    return false;
  }

  return true;
}

void RegisterWindow::onRegisterButtonClicked() {
  if (!validateInput()) {
    return;
  }

  // 收集用户信息
  QString userName = userNameEdit->text();
  QString phone = phoneEdit->text();
  QString email = emailEdit->text();
  QString password = passwordEdit->text();
  QString province = provinceComboBox->currentText();
  QString points = pointsEdit->text();
  QString major = majorComboBox->currentText();

  try {
    // 创建用户管理器并注册用户
    managerSystem::usersManager userManager;
    std::string log = userManager.usersRegister(
        userName.toStdString(), phone.toStdString(),
        tools::calculateHash(password.toStdString()), email.toStdString(),
        province.toStdString(), points.toStdString(), major.toStdString());

    if (log == "User registered successfully") {
      // 注册成功
      // 获取新创建的用户ID
      std::string userId = userManager.getUserIdByName(userName.toStdString());

      // 记录用户注册日志
      tools::Logger::getInstance().log(
          tools::Logger::LogType::USER_REGISTER, userId,
          "新用户注册成功: 用户名=" + userName.toStdString() + ", 邮箱=" +
              email.toStdString() + ", 手机=" + phone.toStdString());

      QMessageBox::information(this, "注册成功",
                               "您已成功注册账号，用户名为: " + userName +
                                   "\n请牢记您的密码。");
      //创建目录
      
    } else {
      // 注册失败
      tools::Logger::getInstance().log(
          tools::Logger::LogType::ERROR, "system",
          "用户注册失败: " + log + ", 尝试用户名: " + userName.toStdString());
      QMessageBox::warning(this, "注册失败", QString::fromStdString(log));
      return;
    }

    // 返回登录界面
    LoginWindow *loginWindow = new LoginWindow();
    loginWindow->setAttribute(Qt::WA_DeleteOnClose);
    loginWindow->show();
    close();
  } catch (const std::exception &e) {
    // 记录异常
    tools::Logger::getInstance().log(
        tools::Logger::LogType::ERROR, "system",
        "注册过程异常: " + std::string(e.what()) +
            ", 尝试用户名: " + userName.toStdString());
    QMessageBox::critical(this, "注册失败",
                          QString("发生错误: %1").arg(e.what()));
  }
}

void RegisterWindow::onBackToLoginClicked() {
  LoginWindow *loginWindow = new LoginWindow();
  loginWindow->setAttribute(Qt::WA_DeleteOnClose);
  loginWindow->show();
  close();
}

void RegisterWindow::paintEvent(QPaintEvent *event) {
  QPainter painter(this);
  painter.setRenderHint(QPainter::Antialiasing);

  // 绘制背景图片
  if (!backgroundImage.isNull()) {
    // 调整图片大小以适应窗口
    QPixmap scaledImage = backgroundImage.scaled(
        this->size(), Qt::KeepAspectRatioByExpanding, Qt::SmoothTransformation);

    QPixmap overlayPixmap(scaledImage.size());
    overlayPixmap.fill(QColor(255, 255, 255, 200));
    QPainter overlayPainter(&scaledImage);
    overlayPainter.setCompositionMode(QPainter::CompositionMode_SourceOver);
    overlayPainter.drawPixmap(0, 0, overlayPixmap);
    overlayPainter.end();

    painter.drawPixmap(0, 0, scaledImage);
  } else {
    painter.fillRect(rect(), QColor("#f8f8f8"));
  }

  QMainWindow::paintEvent(event);
}